import { createNewAsset, uploadAssetApi } from "@/api/uploadAsset";
import { toDataUrlByDownloadAsync } from "./toDataUrlFromUrl";
const DEFAULT_FOLDER = {
  // 默认放入个人工作区-未分类
  ASSET_LABEL_SEQ: "",
  LABEL_TYPE: "F"
};
/**
 * 上传资源
 * @param {*} param0
 * @param {*} param0.base64 base64格式的文件
 * @param {*} param0.url    如果传了 url，没有传base64，自动转base64
 * @returns
 */
export async function uploadAsset({ base64, url, folder = DEFAULT_FOLDER }) {
  if (url && !base64) {
    base64 = await toDataUrlByDownloadAsync(url);
    console.log("base64", base64);
  }
  folder = folder || DEFAULT_FOLDER;
  let params = {
    base: base64,
    srcUrl: ""
  };
  const res = await uploadAssetApi(params);
  const { _success, _data } = res;
  //把图片上传到服务器上
  if (!_success) {
    return { code: -1, _success: false, _msg: "上传base64失败" };
  }

  const arrPath = _data.filePath.split("/");
  const assetName = arrPath[arrPath.length - 1];
  // 将资源和人建立连接
  let assetParams = {
    assetLabelSeq: folder.ASSET_LABEL_SEQ,
    assetName,
    assetType: "",
    extension: _data.extension,
    filePath: _data.filePath,
    fileSize: _data.fileSize,
    labelType: folder.LABEL_TYPE,
    srcUrl: _data.srcUrl
  };
  const finallRes = await createNewAsset(assetParams);
  if (finallRes.code == 0) {
    return { code: 0, _success: true, _msg: "" };
  } else {
    return { code: -1, _success: false, _msg: "资源建立连接失败" };
  }
}
